import json
import logging
import math
import operator
from functools import reduce
from PIL import Image
import filecmp
from flask import Flask, request
from logging import log

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'hello aa!'


@app.route('/image-cut', methods=['POST'])
def request_image_cut():
    """
    处理切分图片http请求
    :return:
    """
    data = json.loads(request.data.decode())
    path = data['path']
    rows = data['rows']
    column = data['column']
    # print(path)
    # print(rows)
    # print(column)
    # try:
    split_image(path, rows, column)
    # except Exception as e:
    #     logging.error('切分图片' + path + '出错')
    #     return result_error()
    return result_success()


def split_image(image_path, columns, rows):
    """
    分割图片
    :param image_path: 图片路径
    :param columns: 列数
    :param rows: 行数
    :return: 分割后的图片列表
    """
    image = Image.open(image_path)
    width, height = image.size
    suffix = image_path.split('.')[-1]
    # image_name = image_path.split('/')[-1].split('.')[0]
    new_path = image_path.replace('.' + suffix, '')
    new_path_list = []

    # 分割图片
    image_list = []
    for i in range(rows):
        for j in range(columns):
            box = (j * width // columns, i * height // rows, (j + 1) * width // columns, (i + 1) * height // rows)
            image_list.append(image.crop(box))

    # 合并相同的图片
    for i, img in enumerate(image_list):
        if len(new_path_list) == 0:
            new_path_list.append([i])
        else:
            flag = False
            for tmp_list in new_path_list:
                # 因为同一list内容肯定相同 所以只需要判断第一个
                if images_are_equal(image_list[tmp_list[0]], image_list[i]):
                    flag = True
                    tmp_list.append(i)
                    break
            if not flag:
                new_path_list.append([i])

    # 设定图片的名字 让内容相同的图片名称相同
    for tmp_list in new_path_list:
        path = f'{new_path}-all{columns*rows}'
        for tmp_i in tmp_list:
            path += f'-part{tmp_i + 1}'
        path += f'.{suffix}'
        image_list[tmp_list[0]].save(path)

    # # 保存图片
    # for i, img in enumerate(image_list):
    #     new_image = f'{new_path}-part{i + 1}.{suffix}'
    #     img.save(new_image)

    # return image_list {image_path}


def images_are_equal(image1, image2):
    """
    比较图片内容是否相同
    :param image1:图片1
    :param image2:图片2
    :return:是否相同
    """

    h1 = image1.histogram()
    h2 = image2.histogram()

    res = math.sqrt(reduce(operator.add, list(map(lambda a, b: (a - b) ** 2, h1, h2))) / len(h1))
    # 比较差异值
    if res < 1:
        return True
    else:
        return False


def result(message, data):
    dic = {'message': message, 'data': data}
    return dic


def result_success(data=None):
    dic = {'message': 'success', 'data': data}
    return dic


def result_error(data=None):
    dic = {'message': 'error', 'data': data}
    return dic


if __name__ == '__main__':
    # logging.basicConfig(filename='error.log', level=logging.DEBUG,
    #                     format='%(asctime)s:%(levelname)s:%(message)s')
    # 默认为5000端口
    app.run()
